|
|
|
|
|
|
|
Opening Binary Access Files |
|
|
|
|
|
|
|
|
Opening a file for binary access is, again, pretty easy. It is similar to the other access mechanisms mentioned earlier, except this time, the length of a row is not necessary. The following syntax is required: |
|
|
|
|
|
|
|
|
Open pathname For Binary As filenumber |
|
|
|
|
|
|
|
|
It's probably good to create a class called BinaryFile that has an openFile() method with this syntax in it. |
|
|
|
|
|
|
|
|
Binary access file operations, though powerful, are sometimes complex. You have much more control over how information is stored, meaning you've got to be careful about what you store. Let's examine a bank transaction information binary file. Consider the following user-defined type (UDT) named BankTransaction: |
|
|
|
|
|
|
|
|
Type Bank Transaction
TransactionID As Integer
TellerName As String * 25
Description As String * 50
MonthlySalary As Currency
HireDate As Long
End Type
Dim SomeTransaction As BankTransaction |
|
|
|
|
|
|
|
|
Each row of SomeTransaction information you save to the binary file consumes 49 bytes. For a handful of rows, this is minuscule. But if you must persist thousands of records to a file daily, and the file accumulates over time, you might need to consider better disk space management. Fixed-length strings almost always result in excess bytes of data as Visual Basic pads each String variable member with spaces to keep the length fixed. Binary access files are good for disk space management. Let's change the BankTransaction UDT as follows: |
|
|
|
|
|
|
|
|
Type BankTransaction
TransactionID As Integer
TellerName As String
Description As String
MonthlySalary As Currency
HireDate As Long
End Type |
|
|
|
|
|
|
|
|
Of course, the benefit of removing the fixed-length attributes of the String variables is that only the precise number of bytes is stored persistently. The disadvantage of binary files is that each row must be accessed sequentially (not to be confused with sequential access files) in order to compute the length of it. Use the Seek statement to go to a certain byte position in the file that has variable-length information; however, there's no exact way to get at a particular record. |
|
|
|
|
|